package com.qh.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qh.common.config.CfgKeyConst;
import com.qh.common.config.Constant;
import com.qh.common.controller.BaseController;
import com.qh.common.utils.QrZxing;
import com.qh.common.utils.R;
import com.qh.pay.api.Order;
import com.qh.pay.api.PayConstants;
import com.qh.pay.api.constenum.OrderState;
import com.qh.pay.api.constenum.OutChannel;
import com.qh.pay.api.constenum.YesNoType;
import com.qh.pay.api.utils.AesUtil;
import com.qh.pay.api.utils.ParamUtil;
import com.qh.pay.api.utils.RSAUtil;
import com.qh.pay.api.utils.RequestUtils;
import com.qh.pay.domain.Merchant;
import com.qh.pay.domain.PayQrConfigDO;
import com.qh.pay.exrick.common.utils.StringUtils;
import com.qh.pay.service.MerchantService;
import com.qh.pay.service.PayQrConfigService;
import com.qh.redis.RedisConstants;
import com.qh.redis.service.RedisUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @ClassName DemoController
 * @Description TODO
 * @Author keph@guahao.com
 * @Date 2019/9/10 15:39
 * @Version 1.0
 */

    @Controller
    @RequestMapping("/demo")
    public class DemoController extends BaseController {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(PayController.class);

    /**
     * @return
     * @Description 选择金额
     */
    @GetMapping("/demo")
    public String qr( Model model) {
       List<String> list=  RedisUtil.getMonAmount(OutChannel.ali.name());

       model.addAttribute("money",list);
       return PayConstants.url_pay_demo;
    }
    @GetMapping("/demo/pay")
    public String pay( Model model) {

        return PayConstants.url_pay_pay;
    }

    @GetMapping("/demo/pay1")
    public String pay1( Model model) {

        return PayConstants.url_pay_pay1;
    }
    /****
     * 商户号
     */
    public final static String merchNo = "SH992255";
       @Autowired
    private MerchantService merchantService;
    /***
     * 支付域名
     */
    public final static String url = RedisUtil.getSysConfigValue(CfgKeyConst.pay_domain)+"pay/order";
    @PostMapping("/demo/money")
    @ResponseBody
    public JSONObject channalPHP(String money) throws Exception{

        Merchant merchant = merchantService.get(merchNo);
      String   mcPublicKey = merchant.getPublicKey();

        String mcPrivateKey = merchantService.getPrivateKey(merchNo);
        JSONObject jsonObj = new JSONObject();
        if(StringUtils.isBlank(money)){
            jsonObj.put("result", 1);
             return jsonObj;
        }
        JSONObject jsObj = new JSONObject();
        String reqTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //商户号
        jsObj.put("merchNo", merchNo);
        //订单号
        jsObj.put("orderNo", reqTime + new Random().nextInt(10000));
        //支付渠道
        jsObj.put("outChannel", OutChannel.ali.name());

        //用户标志
        jsObj.put("userId", "userId");
        //用户标志
        jsObj.put("reqIp", "124.90.47.66");
        //订单标题
        jsObj.put("title", "测试Demo订单");
        //产品名称
        jsObj.put("product", "测试Demo");
        //支付金额 单位 元
        jsObj.put("amount", money);
        //币种
        jsObj.put("currency", "CNY");
        //前端返回地址
        jsObj.put("returnUrl", RedisUtil.getSysConfigValue(CfgKeyConst.pay_domain)+"pay/order/success");
        //后台通知地址
        jsObj.put("notifyUrl", RedisUtil.getSysConfigValue(CfgKeyConst.pay_domain)+"pay/qr/pay/notifyredis");
        //请求时间
        jsObj.put("reqTime", reqTime);

        byte[] context = RSAUtil.encryptByPublicKey(JSON.toJSONBytes(jsObj),mcPublicKey);
        String sign = RSAUtil.sign(context, mcPrivateKey);
        logger.info("签名结果：{}", sign);
        JSONObject jo = new JSONObject();
        jo.put("sign", sign);
        jo.put("context", context);
        jo.put("encryptType", "RSA");
        jo.put("merchNo", merchNo);
        logger.info("请求参数：{}", jo.toJSONString());
        System.out.println(url);
        String result = RequestUtils.doPostJson(url, jo.toJSONString());
        logger.info("选用通道{}", result);
        jo = JSONObject.parseObject(result);

        if ("0".equals(jo.getString("code"))) {
            sign = jo.getString("sign");
            context = jo.getBytes("context");

            if (RSAUtil.verify(context, mcPublicKey, sign)) {
                String source = new String(RSAUtil.decryptByPrivateKey(context, mcPrivateKey));
                logger.info("解密结果：" + source);
                jo = JSONObject.parseObject(source);
                logger.info("网银支付链接地址：{}", jo.getString("code_url"));

                jsonObj.put("result", 0);
                jsonObj.put("url",jo.getString("code_url"));
            } else {

                logger.info("验签失败！{}");
            }
        }else{
            jsonObj.put("result", 2);

        }


        return jsonObj;
    }


}
